package com.yuji.aacar.base;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.PushAgent;
import com.umeng.message.UmengMessageHandler;
import com.umeng.message.UmengNotificationClickHandler;
import com.umeng.message.entity.UMessage;
import com.yuji.aacar.R;
import com.yuji.aacar.bean.beans.PushMessage;
import com.yuji.aacar.bean.response.LoginResponse;
import com.yuji.aacar.core.cores.event.CoreEventCenter;
import com.yuji.aacar.core.cores.fres.CoreFresco;
import com.yuji.aacar.core.cores.services.CoreServiceMediator;
import com.yuji.aacar.core.cores.utils.CoreAppUtil;
import com.yuji.aacar.core.cores.utils.CoreENVConfig;
import com.yuji.aacar.core.cores.utils.LogUtil;
import com.yuji.aacar.core.mvvm.appbase.CoreBaseApplication;
import com.yuji.aacar.core.mvvm.apptask.ViewModelManager;
import com.yuji.aacar.net.config.HttpConfig;
import com.yuji.aacar.service.BaseHttpApi;
import com.yuji.aacar.service.BaseServiceMediator;
import com.yuji.aacar.tools.Tools;
import com.yuji.aacar.tools.UmessageHandler;
import com.yuji.aacar.utils.TimeUtils;
import com.yuji.aacar.widgets.pulltorefresh.util.PtrLocalDisplay;

import org.json.JSONException;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Map;

/**
 * <li>Package:com.yuji.aacar.base</li>
 * <li>Author: lining </li>
 * <li>Date: 2018/2/22</li>
 * <li>Description:   </li>
 */

public class BaseApplication extends CoreBaseApplication{

    public static Context appContext;
    public static Typeface textType;
    public static BaseApplication application;
    private UMessage myMsg;
    private String deviceTokens;
    private PushAgent mPushAgent;


    private static final String DEV_IP= "http://47.97.222.79:8081";
//    private static final String DEV_IP= "http://192.168.199.236:8080";
//    private static final String DEV_IP= "http://192.168.0.82:8080";

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            CoreEventCenter.postMessage(EventConst.PUSH_MESSAGE, "xiaoxi");
        }
    };

    @Override
    public void onCreate() {
        super.onCreate();
        appContext = this;
        application = this;
        PtrLocalDisplay.init(this);
        textType = Typeface.createFromAsset(getApplicationContext().getAssets(), "PingFangSC-Regular.ttf");

        registUMeng();

    }

    private void registUMeng() {

        /**
         * 初始化common库
         * 参数1:上下文，不能为空
         * 参数2:友盟 app key
         * 参数3:友盟 channel
         * 参数4:设备类型，UMConfigure.DEVICE_TYPE_PHONE为手机、UMConfigure.DEVICE_TYPE_BOX为盒子，默认为手机
         * 参数5:Push推送业务的secret
         */
        UMConfigure.init(this, Const.APP_KEY, Const.APP_CHANNEL, UMConfigure.DEVICE_TYPE_PHONE, Const.APP_SECREAT);
        UMConfigure.setLogEnabled(true);
        UMConfigure.setEncryptEnabled(true);
        PushAgent mPushAgent = PushAgent.getInstance(this);
        //注册推送服务，每次调用register方法都会回调该接口
        mPushAgent.register(new IUmengRegisterCallback() {

            @Override
            public void onSuccess(String deviceToken) {
                //注册成功会返回device token
                LogUtil.e("-mPushAgent-deviceToken-", deviceToken);
                if (TextUtils.isEmpty(deviceToken)) {
                    deviceToken = mPushAgent.getRegistrationId();
                }
                if (deviceToken != null && !deviceToken.equals("")) {
                    UserCenter.setDeviceToken(deviceToken);
//                    getSharedPreferences(Const.SHARED_PREFERENCE_NAME, MODE_PRIVATE).edit().putString(Const.DEVICETOKEN_KEY, deviceToken).commit();
                }
            }

            @Override
            public void onFailure(String s, String s1) {

            }
        });

        UmengMessageHandler HandleMessage = new UmengMessageHandler() {
            @Override
            public void dealWithCustomMessage(final Context context, final UMessage msg) {
                LogUtil.e("---收到推送消息11---", msg.toString());
                initNotification(context, msg);
            }

            @Override
            public void dealWithNotificationMessage(Context context, UMessage uMessage) {
                super.dealWithNotificationMessage(context, uMessage);
                LogUtil.e("---收到推送消息22---", uMessage.toString());
            }

            @Override
            public void handleMessage(Context context, UMessage uMessage) {
                super.handleMessage(context, uMessage);
                LogUtil.e("---收到推送消息44---", uMessage.toString());
                LoginResponse user = UserCenter.getCurrentUser();
                if (null != user) {
                    PushMessage message = new PushMessage();
                    message.setTitle(uMessage.title);
                    if (TextUtils.isEmpty(uMessage.custom)){
                        message.setCustom(uMessage.text);
                    } else {
                        message.setCustom(uMessage.custom);
                    }
                    message.setText(uMessage.text);
                    String timeStamp = TimeUtils.getCurrentTime();
                    try {
                        timeStamp = uMessage.getRaw().getString("timestamp");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    message.setTime(timeStamp);

                    ArrayList<PushMessage> messages = UserCenter.getPushMessages(user.getMemberId());
                    ArrayList<PushMessage> messages2 = null;
                    if (null == messages) {
                        messages = new ArrayList<>();
                        messages.add(message);
                        UserCenter.savePushMessage(user.getMemberId(), messages);
                    } else {
                        if (messages.size() > 30) {
                            messages2 = new ArrayList<>();
                            for (int i = 0; i < messages.size() - 10; i++) {
                                messages2.add(messages.get(i));
                            }
                            messages2.add(0, message);
                            UserCenter.savePushMessage(user.getMemberId(), messages2);
                        } else {
                            messages.add(0, message);
                            UserCenter.savePushMessage(user.getMemberId(), messages);
                        }
                    }

                    UserCenter.setNewMessage(user.getMemberId(), "1");
                    handler.sendEmptyMessage(1);
                }
            }

        };

        /**
         * 非自定义消息不会走dealWithCustomAction方法 （自定义消息的通道）
         * 在友盟网站上使用自定义模式发推送后，收到推送后，点击通知消息会走这个回调，打开相应页面
         * 该Handler是在BroadcastReceiver中被调用，故
         * 如果需启动Activity，需添加Intent.FLAG_ACTIVITY_NEW_TASK
         * */
        final UmengNotificationClickHandler notificationClickHandler = new UmengNotificationClickHandler() {
            @Override
            public void dealWithCustomAction(Context context, UMessage uMessage) {
                LogUtil.e("---收到推送消息33---", uMessage.toString());
                myMsg = uMessage;
                Map<String, String> map = uMessage.extra;
                UmessageHandler handler = new UmessageHandler();
                handler.createMessage(map);
                handler.handMsg();
                Intent i = handler.getIntent();
                i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(i);
            }


        };
        mPushAgent.setMessageHandler(HandleMessage);
        mPushAgent.setNotificationClickHandler(notificationClickHandler);
    }


    private Notification initNotification(Context context, UMessage uMessage) {
        Map<String, String> map = uMessage.extra;
        UmessageHandler handler = new UmessageHandler();
        handler.createMessage(map);
        handler.handMsg();
        Intent i = handler.getIntent();
        NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        Notification.Builder builder = new Notification.Builder(context);
        builder.setContentTitle(uMessage.title);
        builder.setContentText(uMessage.text);
        builder.setSmallIcon(R.mipmap.logo);
        builder.setAutoCancel(true);
        builder.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE);
        i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent contentIntent = PendingIntent.getActivity(appContext, R.string.app_name, i, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(contentIntent);
        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.logo);
        } catch (Resources.NotFoundException e) {
            e.printStackTrace();
        }
        builder.setLargeIcon(bitmap);
        Notification n = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
            n = builder.build();
        } else {
            n = builder.getNotification();
        }
        // Notification n = new Notification(R.mipmap.logo, uMessage.title, System.currentTimeMillis());
      /*  n.flags |= Notification.FLAG_AUTO_CANCEL;
        n.defaults |= Notification.DEFAULT_SOUND;
        //设定如何振动
        n.defaults |= Notification.DEFAULT_VIBRATE;*/

        nm.notify(R.string.app_name, n);
        return n;
    }
    @Override
    public void initHttpApis() {
        CoreServiceMediator.initAppAPIs(BaseHttpApi.class);
    }

    @Override
    public void initMVVM() {
        ViewModelManager.getInstance().addViewModelPlist(ViewModelPlist.hashMap);
        //        ViewModelManager.getInstance().setController(exc.getInstance());

    }

    @Override
    public void initGlobleEnvConfig() {
        CoreENVConfig.configurationEnvironment(this);
    }

    @Override
    public void initHttp() {
        HttpConfig.Builder builder = new HttpConfig.Builder();
        builder.addServiceInfos(HttpConfig.createServiceInfo(BaseHttpApi.class.getName(), DEV_IP, "aacar.aacar.cn"))
                .setApplicationContext(getApplicationContext())
                .setToken(Tools.getToken()[0])
                .setUserId(Tools.getToken()[1])
                .setUuUserId(Tools.getuuUserId(this))
                .setDeviceType("andriod_aacar_client")
                .setVersion(Tools.getAppVersionName(this))
                .setDeviceTokens(UserCenter.getDeviceTokens())
                .build();

        System.out.println("--initHttp--userId---"+Tools.getToken());
        System.out.println("--initHttp--userId---"+UserCenter.getDeviceTokens());
    }

    @Override
    public void initFresco() {
        CoreFresco.init(this);
    }

    @Override
    public void initLogUtil() {
        String isDebug = CoreAppUtil.getMetaData(getApplicationContext(), "IS_DEBUG");
        boolean flag = true;
        if (isDebug.contentEquals("YES")) {
            flag = true;
        } else {
            flag = false;
        }
        LogUtil.Builder builder = new LogUtil.Builder();
        builder.allSwitch(flag)
                .errorSwitch(false)
                .writerSwitch(false)
                .logType('e')
                .pathDir("/sdcard/")
                .logFileSaveDays(0)
                .logFileName("Log.txt")
                .myLogSdf(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))
                .logfile(new SimpleDateFormat("yyyy-MM-dd")).build();

    }

    @Override
    public void initAppServicesMediators() {
        CoreServiceMediator.initAppServicesMediators(new BaseServiceMediator());
    }

    @Override
    protected void initDB() {

    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        MobclickAgent.onKillProcess(this);
    }

}
